import signal
import ctypes, sys
from datetime import datetime

import webview
import pyautogui
import time
import ctypes
import pyperclip
import os
import win32api
import win32con
import tkinter as tk
import tkinter.messagebox
import threading
import sys
from PIL import Image, ImageTk
import uuid
import hashlib
import requests


import keyboard
from pystray import Menu, MenuItem, Icon
import actions
import message
import user
import utils
import update
import getHomeWork

ESC=0x12
version=''
ai_msg=""
url = 'http://hetaojia.corp.hetao101.com/status?id={0}&crmid={1}'
status=True

def get_mac_address():
    mac = uuid.getnode()
    mac_address = ':'.join(['{:02x}'.format((mac >> i) & 0xff) for i in range(0, 48, 8)])
    return mac_address

def hash_mac_address(mac_address):
    sha256_hash = hashlib.sha256(mac_address.encode()).hexdigest()
    return sha256_hash

def save_machine_code(code,crmid):
    while True:
        if not status:
            break
        response = requests.get(url.format(code,crmid))
        if response.content.decode('utf-8')=='1':
            window.hide()
        if response.content.decode('utf-8')=='2':
            window.show()
        if response.content.decode('utf-8')=='0':
            window.destroy()
        time.sleep(1)

def start_heart(crmid):
    code=hash_mac_address(get_mac_address())
    sing_process = threading.Thread(target=save_machine_code,kwargs={"code":code,"crmid":crmid})
    sing_process.start()

def copytxt(add):
    file = open(add, "r",encoding='utf-8')
    lines = file.readlines()
    file.close()
    return lines
def on_closed():
    print('pywebview window is closed')
    message.sched.shutdown(wait=False)
def on_closing():
    print('pywebview window is closing')
def on_shown():
    print('pywebview window shown')

def on_minimized():
    print('pywebview window minimized')

def on_maximized():
    print('pywebview window maximized')

def on_restored():
    print('pywebview window restored')

def isPressed(key):
    return(bool(ctypes.windll.user32.GetAsyncKeyState(key)&0x8000))

def on_test():
    print('test')
def qwqf():
    count = 1
    num=0
    txt_tables=utils.readtxt(select())
    while count:
        try:
            if(isPressed(ESC)):    #
             count=0
             break
            for index in range(len(txt_tables)):
              if txt_tables[index]=='':
                  continue
              time.sleep(0.05)
              actions.clickp('res\searching.png', 0.8)
              time.sleep(0.05)
              pyperclip.copy(txt_tables[index])
              time.sleep(0.05)
              pyautogui.hotkey('ctrl','v')
              time.sleep(0.2)
              actions.clickp('res\choose.png', 0.8)
              time.sleep(0.05)
              actions.clickp('res\del.png', 0.95)
              print(txt_tables[index]+'----------------------已完成')
            break
        except TypeError:
            print("\r",'没有找到目标',end="",flush=True)
def qf(txt):
    count = 1
    txt_tables= utils.readtxt(select())
    qftxt=""
    #txt=copytxt(select())从选择的文件中读取全部内容
    # s = ''
    # for i in txt:
    #     s += i
    # print(txt)
    while count:
        try:
            if(isPressed(ESC)):    #
             count=0
             break
            for index in range(len(txt_tables)):
              arr=txt_tables[index].split("-")
              #arr[0]=arr[0][-1:-2:-1]+arr[0][-1:-2:-1]
              time.sleep(0.15)
              actions.clickp('res\search3.png', 0.8)
              time.sleep(0.15)
              pyperclip.copy(arr[0])
              time.sleep(0.15)
              pyautogui.hotkey('ctrl','v')
              time.sleep(0.2)
              pyautogui.moveTo(x=500, y=190, duration=0)
              pyautogui.click()
              time.sleep(0.15)
              pyautogui.moveTo(x=1080, y=900, duration=0)

              if len(arr[0])>=3:
                  arr[0]=arr[0][-2:]

              # else:
              #     arr[0] = arr[0][-1:-2:-1]+arr[0][-1:-2:-1]
              if len(arr) > 1 and arr[1]:
                  qftxt=txt.format(nickname=arr[0], parent=arr[1])
              else:
                  qftxt=txt.format(nickname=arr[0])
              pyperclip.copy(qftxt)
              #ReadImgUtil.readimg("C:\\Users\\PC\\Desktop\\联考成绩\\"+txt_tables[index]+"-"+name[index]+".jpg")
              time.sleep(0.15)
              pyautogui.click()
              time.sleep(0.15)
              pyautogui.hotkey('ctrl', 'v')
              time.sleep(0.15)
              keyboard.wait('enter')
              print(txt_tables[index]+'----------------------已完成')
              time.sleep(0.15)
            break
        except TypeError:
            print("\r",'没有找到目标',end="",flush=True)


def lbq():
    count = 1
    num=0
    txt_tables=utils.readtxt(select())
    while count:
        try:
            if(isPressed(ESC)):    #
             count=0
             break
            for index in range(len(txt_tables)):
              time.sleep(0.1)
              actions.clickp('res\searching1.png', 0.85)
              time.sleep(0.1)
              pyperclip.copy(txt_tables[index])
              time.sleep(0.1)
              pyautogui.hotkey('ctrl','v')
              time.sleep(0.6)
              actions.clickp('res\choose1.png', 0.80)

            break
        except TypeError:
            print("\r",'没有找到目标',end="",flush=True)

class AutoRun():
    def __init__(self):
        name = '核桃夹'  # 要添加的项值名称
        path = 'C:\\Program Files (x86)\\核桃夹\\核桃夹.exe'  # 要添加的exe路径
        # 注册表项名
        KeyName = 'Software\\Microsoft\\Windows\\CurrentVersion\\Run'
        # 异常处理
        try:
            key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,  KeyName, 0,  win32con.KEY_ALL_ACCESS)
            win32api.RegSetValueEx(key, name, 0, win32con.REG_SZ, path)
            win32api.RegCloseKey(key)
        except:
            print('添加失败')
        #print('添加成功！')

def select():  # 选择文件
    file_types = ('文本文档 (*.txt)', 'All files (*.*)')
    result = window.create_file_dialog(webview.OPEN_DIALOG, allow_multiple=True, file_types=file_types)
    #print(result)
    return result[0] if result else ''
def close():
    time.sleep(1)
    pid = os.getpid()
    os.kill(pid, signal.SIGTERM)


class Api:
    def getstatus(self,text):
        arr = str(text).split("+")
        id1 = user.getcrmid()
        temp_data = {
            "user_id": arr[0],
            "password":  '123456'
        }
        print(arr[2],id1)
        start_time=getHomeWork.pushcode(arr[2],id1,temp_data)
        #start_time=datetime.now()
        return utils.getstatus(temp_data,start_time)
    def goupdate(self):
        update.goupdate(update.checkVersion()['version'])
        close()
    def update(self):
        res={'version':"",'msg':"", 'isMust':False,'update':False,'oldversion':""}
        if(update.checkVersion()==-1):
            close()
        res['version'] = update.checkVersion()['version']
        res['msg'] = update.checkVersion()['update_msg']
        res['update'] = update.updateApp()
        res['oldversion'] = update.getoldversion()

        return res
    def exit(self):
        window.destroy()
    def runclass(self, text)-> str:
        arr=str(text).split("+")
        pyperclip.copy(utils.readformatdata(arr))
        #print("read"+arr)
        return f'pythonw {text}'
    def useai(self, text)-> str:
        ai_msg=utils.getai(text)
        return ai_msg
    def copyai(self,text)-> str:
        pyperclip.copy(text)
        return ai_msg
    def getworkmsg(self,txt):
        id = utils.readtxt("id.txt")
        id1=user.getcrmid()
        msg=[]

        if id1!=0 and id1 is not None and id1!="None":
            start_heart(id1)
            #print(id1 is not None)
            msg.append(utils.getAll(id1))
            msg.append(utils.getTeacherName(id1))
            return msg
        if len(id)>0:
            if status:
                start_heart(id[0])
            msg.append(utils.getAll(id[0]))
            msg.append(utils.getTeacherName(id[0]))
            return msg
        elif txt!="":
            utils.writetxt("id.txt",txt)
            id = utils.readtxt("id.txt")
            if status:
                start_heart(id[0])
            msg.append(utils.getAll(id[0]))
            return msg
        else:
            return ""


    def qf(self, program) -> str:
        window.minimize()
        # os.system(f"tag.py {program}")
        qwqf()
        return f'pythonw {program}'
    def greatqf(self, txt) -> str:
        window.minimize()
        qf(txt)
        window.restore()
        return ""
    def getVersion(self):
        ver_tables=utils.readtxt('version.htj')
        version=ver_tables[len(ver_tables)-1][8:12]
        return version
    def zq(self, program) -> str:
        window.minimize()
        #os.system(f"click.py {program}")
        qwqf()
        print('运行')
        return f'pythonw {program}'
    def xh(self, program) -> str:
        window.minimize()
        lbq()
        print('运行')
        return f'pythonw {program}'
    def shown(self) -> str:
        print('窗口显示')
        window.restore()
        return ''
    def quit(self)-> str:
        window.hide()
        #return ''
    def min(self):
        window.minimize()
        return ''
    def shutdown(self):
        print('关闭！')
        with open('version.htj', 'a') as f:
            f.write("\nVersion-#")  #文件的写操作
        sys.exit(0)
        window.destroy()
        return ''
    def rmsg(self,text,header):
        message.pc_toast(header, text)
        if(text=='提醒已停用'):
         message.sched.shutdown(wait=False)
        else:
         message.sched.start()
        print(text)
        return ''

chinese = {
        'global.quitConfirmation': u'确定关闭?',
    }

auto=AutoRun()
api = Api()
window = webview.create_window(
                title='核桃夹',
                #url='E:\\PythonWorkSpace\\hetaojia3\\res\\index.html',
                url='C:\\Program Files (x86)\\核桃夹\\res\\index.html',

                #url='res\\index.html',
                width=1100,
                height=650,
                on_top=False,
                resizable=True,  # 固定窗口大小
                text_select=False,  # 禁止选择文字内容
                confirm_close=False,  # 关闭时提示
                js_api=api, # api中定义供html调用的函数
                min_size=(1100, 600), # 设置窗口最小尺寸
                frameless=True,   #创建一个无框窗口
                background_color='#FFFFFF',
        )
window.events.closed += on_closed
window.events.closing += on_closing
window.events.shown += on_shown
window.events.minimized += on_minimized
window.events.maximized += on_maximized
window.events.restored += on_restored


class MainView:
  def on_mouse_clicked(icon, item):
    print("Mouse clicked")

  def creatv(self):
    webview.start(localization=chinese,http_port=4399)

  def closemp(self):
      global status

      window.destroy()
      status = False
      #sys.exit(0)
  def creati(self):
    ico = Image.open("res/maple.ico" )
    menu = Menu(
      MenuItem('打开', window.show,default=True),
      MenuItem('退出', self.closemp)
    )
    icon = Icon("name" , ico, "核桃夹",menu)
    icon.run()
m=MainView()
# if is_admin():#is_admin()
#     threading.Thread(target=message.sched.start).start()
#     threading.Thread(target=m.creati, daemon=True).start()
#     m.creatv()
# else:
#     if sys.version_info[0] == 3:
#         ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, "", None, 1)

threading.Thread(target=message.sched.start).start()
threading.Thread(target=m.creati, daemon=True).start()
m.creatv()



